package com.crm.common.utils.sign;


import com.alibaba.fastjson2.JSON;

import org.apache.commons.codec.digest.DigestUtils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import lombok.extern.slf4j.Slf4j;

/**
 *
 * 加签/验签工具类
 *
 * @author qsh
 * @date 2018/12/19 上午11:18
 *
 */
@Slf4j
public class SignUtil {
    /**
     * 得到签名
     * @param params 参数集合,不含密钥secret
     * @param secret 分配的密钥secret
     * @return sign 签名
     */
    public static String getSign(Map<String, String> params, String secret) {
        StringBuilder sb = new StringBuilder();
        // 先对请求参数去重并排序
        Set<String> keySet = params.keySet();
        TreeSet<String> sortSet = new TreeSet<>(keySet);
        // 将排序后的参数与其对应值，组合成 参数=参数值 的格式，并且把这些参数用 & 字符连接起来，此时生成的字符串为待签名字符串
        for (String key : sortSet) {
            String value = params.get(key);
            sb.append(key).append("=").append(value).append("&");
        }
        sb.append("secret=").append(secret);
        byte[] md5Digest;
        // Md5加密得到sign
        md5Digest = getMd5Digest(sb.toString());
        return byte2hex(md5Digest);
    }

    /**
     * 获取md5信息摘要
     * @param data 需要加密的字符串
     * @return bytes 字节数组
     */
    private static byte[] getMd5Digest(String data) {
        byte[] bytes = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            bytes = md.digest(data.getBytes(StandardCharsets.UTF_8));
        } catch (GeneralSecurityException gse) {
            log.error("生成签名错误", gse);
        }
        return bytes;
    }

    /**
     * 将字节数组转化为16进制
     * @param bytes 字节数组
     * @return sign 签名
     */
    private static String byte2hex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (byte aByte : bytes) {
            String hex = Integer.toHexString(aByte & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }
        return sign.toString();
    }


    /**
     * 加签方法
     * @param bean Javabean对象
     * @param key 加签盐值
     * @return
     */
    public static String sign(Object bean, String key){
        return sign(beanToMap(bean), key);
    }

    /**
     * 加签方法
     * @param map Map对象
     * @param key 加签盐值
     * @return
     */
    public static String sign(Map<String, Object> map, String key){
        String genSign = "";
        try {
            //默认将按照key值进行升序排序
            TreeMap treeMap = sortMap(map);
            //原始签文
            String orgStr = JSON.toJSONString(treeMap).concat(key);
            log.info("加签原文："+orgStr);
            //指定编码格式
            genSign = DigestUtils.md5Hex(orgStr.getBytes("UTF-8"));
            log.info("加签密文："+genSign);
        }catch (Exception e){
            log.info("加签失败",e);
        }
        return genSign;
    }

    /**
     * 验签方法
     * @param bean Javabean对象
     * @param key 验签盐值
     * @param sign 签名密文
     * @return
     */
    public static boolean verify(Object bean, String key, String sign){
        boolean flag = false;
        try{
            Map paramsMap = beanToMap(bean);
            //默认将按照key值进行升序排序
            TreeMap treeMap = sortMap(paramsMap);
            //原始签文
            String orgStr = JSON.toJSONString(treeMap).concat(key);
            log.info("验签原文："+orgStr);
            //指定编码格式
            String genSign = DigestUtils.md5Hex(orgStr.getBytes("UTF-8"));
            log.info("验签密文："+genSign);
            if(genSign.equals(sign)){
                flag = true;
            }
        }catch (Exception e){
            log.info("验签失败",e);
        }
        return flag;
    }

    /**
     * 将JavaBean对象转化为Map
     * @param bean
     * @return
     */
    public static Map beanToMap(Object bean){
        Map returnMap = new HashMap();
        try {
            Class type = bean.getClass();
            BeanInfo beanInfo = Introspector.getBeanInfo(type);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            //循环获取bean属性和值放入map中
            for (int i = 0; i < propertyDescriptors.length; i++) {
                PropertyDescriptor descriptor = propertyDescriptors[i];
                String propertyName = descriptor.getName();
                //忽略sign属性
                if (!"sign".equals(propertyName)&&!"class".equals(propertyName)) {
                    Method readMethod = descriptor.getReadMethod();
                    Object result = readMethod.invoke(bean, new Object[0]);
                    returnMap.put(propertyName, result);
                }
            }
        }catch (Exception e){
            log.info("beanToMap失败",e);
        }
        return returnMap;
    }

    /**
     * map排序
     *
     * @param map
     * @return
     */
    private static TreeMap sortMap(Map<String, Object> map) {
        TreeMap treeMap = new TreeMap();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() instanceof Map) {
                TreeMap subTreeMap = sortMap((Map) entry.getValue());
                treeMap.put(entry.getKey(), subTreeMap);
            } else {
                treeMap.put(entry.getKey(), entry.getValue());
            }
        }
        return treeMap;
    }


    public static void main(String args[]){
        Map<String, String> params = new HashMap<>();
        String secret = "";
        getSign(params,secret);
    }
}
